package io.qar.mq.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.qar.commons.dynamic.datasource.annotation.DataSource;
import io.qar.mq.dao.OrderCreditsDao;
import io.qar.mq.dao.OrdersDao;
import io.qar.mq.dao.TransactionLogDao;
import io.qar.mq.entity.OrderCreditsEntity;
import io.qar.mq.entity.OrdersEntity;
import io.qar.mq.entity.TransactionLogEntity;
import io.qar.mq.service.TransactionLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @program: qar-cloud
 * @description:
 * @author: yyyyjinying
 * @create: 2023-10-18 14:32
 **/
@Service
public class TransactionLogServiceImpl implements TransactionLogService {
    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private OrderCreditsDao orderCreditsDao;

    @Autowired
    private TransactionLogDao transactionLogDao;

    public boolean hasTransctionId(String id) {
        int i = transactionLogDao.deleteById(id);
        return i > 0;
    }

    // 本地事务
    @Override
    @Transactional
    public void createOrder(OrdersEntity ordersEntity, String transactionId) {
        ordersDao.insert(ordersEntity);
        int id = ordersEntity.getId();
        TransactionLogEntity transactionLogEntity = new TransactionLogEntity();
        transactionLogEntity.setBusiness("createOrder");
        transactionLogEntity.setForeign_key(String.valueOf(id));
        transactionLogEntity.setId(transactionId);
        transactionLogDao.insert(transactionLogEntity);
    }

    @Override
    @Transactional
    public void insertOrderCredits(OrdersEntity ordersEntity) {
        QueryWrapper<OrderCreditsEntity> queryWrapper = new QueryWrapper<>();
        int orderId = ordersEntity.getId();
        queryWrapper.eq("order_id", orderId);
        OrderCreditsEntity result = orderCreditsDao.selectOne(queryWrapper);
        if (result == null) {
            OrderCreditsEntity orderCreditsEntity = new OrderCreditsEntity();
            orderCreditsEntity.setOrder_id(orderId);
            orderCreditsEntity.setTotal(1);
            orderCreditsEntity.setUser_id(ordersEntity.getUser_id());
            orderCreditsDao.insert(orderCreditsEntity);
        }

    }
}
